﻿window.addEventListener("load", function () {
  gBrowser.addEventListener("load", au_com_felsoft_antiporn.Init, true);
}, false);

var au_com_felsoft_antiporn = {

/////////////////// COMMON FUNCTIONS //////////////////
server_url:'http://antiporn.felsoft.com.au/',
exclude_sites:'',
block_sites:'',
keywords:'',
m_strict_mode:0,
m_urlblacklist_mode:0,
m_flag:0,
m_login:'',
m_md5salt:'',
m_computer:'',

log: function(msg)
{
// disable for production..

// var m_log = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
// m_log.logStringMessage(msg);
},

notFoundPageURL: "about:neterror?e=dnsNotFound&u=@URL&c=UTF-8&d=Firefox%20can't%20find%20the%20server%20at%20@URL.",

loadingPageHtml: "<head><link href=\"http://antiporn.felsoft.com.au/css/google_chrome_loading.css\" rel=\"stylesheet\" type=\"text/css\" /></head><body><div id=\"wrap\"><div id=\"main\"></div></div><div id=\"footer\"><span style='background: #efefef; color:#999;'>&nbsp;Waiting for @URL&nbsp;</span></div></body>",

getHostname: function(str) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return str.match(re)[1].toString();
},

trim: function(str) {
	return str.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
},

logRequest: function(url) {
// Log using async call

	var formData = "u="+au_com_felsoft_antiporn.m_login;
	formData = formData +"&p="+au_com_felsoft_antiporn.m_md5salt;
	formData = formData +"&c="+au_com_felsoft_antiporn.m_computer;
	formData = formData +"&url="+encodeURIComponent(url);

	var xhrlog = new XMLHttpRequest();
	xhrlog.onreadystatechange = function() {}
	var urllog=au_com_felsoft_antiporn.server_url+"rpc_log_p.php";
	xhrlog.open("POST", urllog, true);
	xhrlog.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhrlog.setRequestHeader("Content-Length", formData.length);
	xhrlog.send(formData);
},
isWhiteListed: function(m_url) {
	var i;
	for(i in au_com_felsoft_antiporn.exclude_sites)
	{
		if(au_com_felsoft_antiporn.exclude_sites[i]=='')
			continue;
		if(m_url.indexOf(au_com_felsoft_antiporn.trim(au_com_felsoft_antiporn.exclude_sites[i]))!=-1)
		{
			return true;
		}
	}
	return false;
},

isCustomBlackListed: function(m_url,aEvent) {
	for(i in au_com_felsoft_antiporn.block_sites)
	{
		if(au_com_felsoft_antiporn.block_sites[i]=='')
			continue;
		if(m_url.indexOf(au_com_felsoft_antiporn.trim(au_com_felsoft_antiporn.block_sites[i]))!=-1)
		{					
				// stop
				au_com_felsoft_antiporn.log('BLACKLISTED!');
				var notFoundPage_tmp = au_com_felsoft_antiporn.notFoundPageURL.replace(/@URL/gi,au_com_felsoft_antiporn.getHostname(m_url));
				aEvent.originalTarget.location.href=notFoundPage_tmp;
				return true;
		}
	}
	return false;
},


isBlackListed: function(aEvent,m_html_data,m_url) {
	var i;	
	if(au_com_felsoft_antiporn.m_urlblacklist_mode == '1')
	{
		var xhr_1 = new XMLHttpRequest();
		var url=au_com_felsoft_antiporn.server_url+"urlblacklist.php?url="+encodeURIComponent (m_url);
		au_com_felsoft_antiporn.log('URL BLACKLIST: '+url);
		xhr_1.onreadystatechange = function() {
		au_com_felsoft_antiporn.log('URL BLACKLIST STATE: '+xhr_1.readyState);
			  if (xhr_1.readyState == 4) {
			  au_com_felsoft_antiporn.log('URL BLACKLIST RESPONSE: '+xhr_1.responseText);
				if(xhr_1.responseText == 'stop')
				{					
					au_com_felsoft_antiporn.log('BLACKLISTED!');
					var notFoundPage_tmp = au_com_felsoft_antiporn.notFoundPageURL.replace(/@URL/gi,au_com_felsoft_antiporn.getHostname(m_url));
					aEvent.originalTarget.location.href=notFoundPage_tmp;				
					return;
				}
				else
				{
					if(au_com_felsoft_antiporn.isCustomBlackListed(m_url,aEvent))
						return;
				}
				////
				if(au_com_felsoft_antiporn.m_strict_mode != '1')
				{	
					au_com_felsoft_antiporn.log('onPageLoad() URL = '+m_url);		
					au_com_felsoft_antiporn.log('checkForKeywords()');
					au_com_felsoft_antiporn.checkForKeywords(aEvent,m_html_data,m_url);
				}
			}
		}
		xhr_1.open("GET", url, true);
		xhr_1.send();
	}
	else
	{
		if(au_com_felsoft_antiporn.isCustomBlackListed(m_url,aEvent))
			return;
		////
		if(au_com_felsoft_antiporn.m_strict_mode != '1')
		{	
			au_com_felsoft_antiporn.log('onPageLoad() URL = '+m_url);		
			au_com_felsoft_antiporn.log('checkForKeywords()');
			au_com_felsoft_antiporn.checkForKeywords(aEvent,m_html_data,m_url);
		}
	}
},

checkForKeywords: function(event,m_html_data,m_url) {
	var i;
	var loading =false;
	for(i in au_com_felsoft_antiporn.keywords)
	{
		if(au_com_felsoft_antiporn.keywords[i]=='')
			continue;
		au_com_felsoft_antiporn.log('Checking Keyword .. '+au_com_felsoft_antiporn.keywords[i]);
		if(m_html_data.toLowerCase().indexOf(au_com_felsoft_antiporn.keywords[i].toLowerCase())!=-1)
		{		
				au_com_felsoft_antiporn.log("Keyword Found!");
				loading =true;
				var html_tag = event.originalTarget.removeChild(event.originalTarget.getElementsByTagName('html')[0]);
				var LoadingPage_tmp = au_com_felsoft_antiporn.loadingPageHtml.replace(/@URL/gi,au_com_felsoft_antiporn.getHostname(m_url));
				var element_html_loading = event.originalTarget.createElement("html");
				element_html_loading.innerHTML=LoadingPage_tmp;
				event.originalTarget.appendChild(element_html_loading);
			
					au_com_felsoft_antiporn.log("Loading Page Simulated!");
		
					var formData = "u="+au_com_felsoft_antiporn.m_login;
					formData = formData +"&p="+au_com_felsoft_antiporn.m_md5salt;
					formData = formData +"&c="+au_com_felsoft_antiporn.m_computer;
					formData = formData +"&url="+encodeURIComponent(m_url);
		
		
				var url=au_com_felsoft_antiporn.server_url+"rpc_access_p.php";
				var xhr1 = new XMLHttpRequest();
				xhr1.onreadystatechange = function() {
				  if (xhr1.readyState == 4) {
				  au_com_felsoft_antiporn.log("Response : "+xhr1.responseText);
					if(xhr1.responseText == 'stop')
					{
						au_com_felsoft_antiporn.log("Not found page redirected");
						var notFoundPage_tmp = au_com_felsoft_antiporn.notFoundPageURL.replace(/@URL/gi,au_com_felsoft_antiporn.getHostname(m_url));				
						event.originalTarget.location.href = notFoundPage_tmp;
					}
					else
					{
						au_com_felsoft_antiporn.log("Original Page Loaded!");
						event.originalTarget.removeChild(element_html_loading);
						event.originalTarget.appendChild(html_tag);
					}			
				  }
				 }
				xhr1.open("POST", url, true);
				xhr1.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				xhr1.setRequestHeader("Content-Length", formData.length);
				au_com_felsoft_antiporn.log("Sending Notification to Parent.");				
				xhr1.send(formData);
				return;		
		}
	}
},

loadSettings: function()
{
////////////////////////////////////SETTINGS (ASYNC REQUEST)///////////////////////////
	if(au_com_felsoft_antiporn.m_flag == 0)
	{		
		// To make sure it is called just once on first load of browser...
		try
		{
			var prefManager = Components.classes["@mozilla.org/preferences-service;1"]
									.getService(Components.interfaces.nsIPrefBranch);
			var myLoginManager = Components.classes["@mozilla.org/login-manager;1"].
							  getService(Components.interfaces.nsILoginManager);
			var logins = myLoginManager.findLogins({}, 'chrome://antiporn', null, 'Login Information');
			
			au_com_felsoft_antiporn.m_flag	= 1;
			au_com_felsoft_antiporn.m_login = logins[0].username;
			au_com_felsoft_antiporn.m_md5salt = logins[0].password;
			
			au_com_felsoft_antiporn.m_computer = prefManager.getCharPref("extensions.antiporn.computer");	
		}
		catch(ex){au_com_felsoft_antiporn.log("Error retrieving account settings!");}
	
		var xhr = new XMLHttpRequest();
		
		var formData = "u="+au_com_felsoft_antiporn.m_login;
		formData = formData +"&p="+au_com_felsoft_antiporn.m_md5salt;		
		xhr.onreadystatechange = function() {
		  if (xhr.readyState == 4) {
		  au_com_felsoft_antiporn.log("SETTINGS RESPONSE: "+xhr.responseText);
			if(xhr.responseText != 'Unauthorized')
			{				
				var resp_tmp = xhr.responseText.split('|');
				var m_exclude_sites_array = resp_tmp[0];
				au_com_felsoft_antiporn.exclude_sites = m_exclude_sites_array.split(',');
				var m_block_sites_array = resp_tmp[1];
				au_com_felsoft_antiporn.block_sites = m_block_sites_array.split(',');
				var m_keywords_array = resp_tmp[2];
				au_com_felsoft_antiporn.keywords = m_keywords_array.split(',');
				au_com_felsoft_antiporn.m_strict_mode = resp_tmp[3];
				au_com_felsoft_antiporn.m_urlblacklist_mode = resp_tmp[4];				
			}
		  }
		}
		var url=au_com_felsoft_antiporn.server_url+"rpc_settings_p.php";
		au_com_felsoft_antiporn.log("SETTINGS REQUEST: "+url);
		xhr.open("POST", url, true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.setRequestHeader("Content-Length", formData.length);
		xhr.send(formData);
	}
	////////////////////////////////////
},

///////////////////////////////////////////////////////

  Init: function() {
	au_com_felsoft_antiporn.loadSettings();
  
   // For accessing browser window from sidebar code.
    var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
               .getInterface(Components.interfaces.nsIWebNavigation)
               .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
               .rootTreeItem
               .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
               .getInterface(Components.interfaces.nsIDOMWindow);
    var gBrowser = mainWindow.gBrowser;
    if (gBrowser.addEventListener) {
        gBrowser.addEventListener("load",au_com_felsoft_antiporn.onPageLoad,true);
    }   
	
  },

  onPageLoad: function(aEvent) {
		var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
		
		if(doc.location == undefined)
			return;
		
		var m_url = doc.location.href;
				
		if(m_url.indexOf('http')!=0)
			return;	

		if(m_url.indexOf('felsoft.com.au')!=-1)
			return;	
			
		if(m_url.indexOf('google.')!=-1 && m_url.indexOf('q=')!=-1  && m_url.indexOf('safe=')==-1)
		 {
			content.document.location.href = m_url+'&safe=high';
			// &as_qdr=all
			return;
		 }

			
			
		var m_html_data = doc.getElementsByTagName('html')[0].innerHTML; // just used for keyword search
			
		if (aEvent.originalTarget instanceof HTMLDocument) {
		var win = aEvent.originalTarget.defaultView;
		// return if it is called from a iframe
		if (win.frameElement) {
		  return;
		}
		
		
		au_com_felsoft_antiporn.log('Log the request');
		au_com_felsoft_antiporn.logRequest(m_url); // Log the request
		
		au_com_felsoft_antiporn.log('checking for whitelisted');
		if(au_com_felsoft_antiporn.isWhiteListed(m_url))	//Check if this site is whitelisted
		{
			au_com_felsoft_antiporn.log('WHITELISTED!');
			return;
		}
		
		if(au_com_felsoft_antiporn.m_strict_mode == '1')
		{	
			// block
			var notFoundPage_tmp = au_com_felsoft_antiporn.notFoundPageURL.replace(/@URL/gi,au_com_felsoft_antiporn.getHostname(m_url));
			content.document.location.href=notFoundPage_tmp;
			return;
		}
			
		au_com_felsoft_antiporn.log('checking for blacklisted');
		au_com_felsoft_antiporn.isBlackListed(aEvent,m_html_data,m_url); // Async Request		
	  }
  }
}
